<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-card>
          <el-button type="primary" @click="addClick()">添加角色</el-button>
        </el-card>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 == 0 ? 'bdtop' : 'bdbottom', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  @close="removeRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="['bdtop', i2 == 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightById(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightById(scope.row, item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRights(scope.row)"
              >设置</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
      <!-- 新增对话框区域 -->
      <el-dialog
        title="添加角色"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="addDialogClose"
      >
        <el-form
          :model="addRoleForm"
          :rules="addRoleRules"
          ref="addRoleRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoleOk">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 设置权限对话框 -->
    <el-dialog
      title="添加权限"
      :visible.sync="addRightsDialogVisible"
      width="40%"
      @close="setRightsClose"
    >
      <el-tree
        :props="props"
        :data="rightsListTree"
        show-checkbox
        default-expand-all
        node-key = "id"
        :default-checked-keys ="arrKey"
        ref="treeRef"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightsOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      editDialogVisible: false,
      addRightsDialogVisible: false,
      rightsListTree: [],
      arrKey :[],
      roleId:"",
      props: {
        label: 'authName',
        children: 'children',
      },
      isAdd: true,
      addRoleForm: {
        id: null,
        roleName: '',
        roleDesc: '',
      },
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      let { data: res } = await this.$http.get('roles')
      if (res.meta.status != 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      //   this.$message.success('获取角色列表成功')
    },
    addClick() {
      this.editDialogVisible = true
      this.isAdd = true
    },
    // 监听对话框close事件
    addDialogClose() {
      ;(this.addRoleForm = {
        id: null,
        roleName: '',
        roleDesc: '',
      }),
        // resetFields 清空表单
      this.$refs.addRoleRef.resetFields()
    },
    addRoleOk() {
      this.$refs.addRoleRef.validate(async (value) => {
        if (!value) return
        if (this.isAdd) {
          let { data: res } = await this.$http.post('roles', {
            roleName: this.addRoleForm.roleName,
            roleDesc: this.addRoleForm.roleDesc,
          })
          if (res.meta.status != 201) {
            return this.$message.error('创建角色失败')
          }
          this.$message.success('创建角色成功')
          this.getRolesList()
          this.editDialogVisible = false
        } else {
          let { data: res } = await this.$http.put(
            'roles/' + this.addRoleForm.id,
            this.addRoleForm
          )
          if (res.meta.status != 200) {
            return this.$message.error('修改角色失败')
          }
          this.$message.success('修改角色成功')
          this.getRolesList()
          this.editDialogVisible = false
        }
      })
    },
    async editRole(id) {
      this.addRoleForm.id = id
      let { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('获取角色失败')
      }
      this.addRoleForm.roleName = res.data.roleName
      this.addRoleForm.roleDesc = res.data.roleDesc
      this.editDialogVisible = true
      this.isAdd = false
    },
    async deleteRole(id) {
      let resultConfirm = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(resultConfirm)
      if (resultConfirm != 'confirm') {
        return this.$message.warning('取消删除')
      }
      let { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    async removeRightById(role, rightId) {
      let resultConfirm = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(resultConfirm)
      if (resultConfirm != 'confirm') {
        return this.$message.warning('取消删除')
      }
      let { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除权限失败')
      }
      this.$message.success('删除权限成功')
      role.children = res.data
      //   this.getRolesList();
    },
    // 设置权限
    async setRights(node) {
      this.roleId = node.id
      let { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status != 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsListTree = res.data
      this.getChildrenId(node,this.arrKey)
      console.log(this.rightsListTree)
      this.addRightsDialogVisible = true
    },
    setRightsClose(){
      this.arrKey = []
    },
    // 递归调用三级权限赋值
    getChildrenId(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getChildrenId(element,arr)
      });
    },
    async setRightsOk() {
      const arr = [
        ...this.$refs.treeRef.getHalfCheckedKeys(),
        ...this.$refs.treeRef.getCheckedKeys(),
      ]
      console.log(arr);
      const param = arr.join(',');
      let { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,{rids:param})
      if (res.meta.status != 200) {
        return this.$message.error('修改权限失败')
      }
      this.$message.success('修改权限成功')
      this.arrKey = []
      this.getRolesList();
      this.addRightsDialogVisible = false
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>>
